<?php require('header.php') ?>
<script type="text/javascript">
	
		/**
		*showDate takes string date which is the id of an html form input to turn into a DatePicker
		*/
      	function showDate(date) {      	      	
			dpck   = new DatePicker({
	  		relative  : date,
	        language  : 'en',
	        keepFieldEmpty : 'true',
	    	dateFormat: [ ["yyyy","mm","dd"], "-"]
		    });
		}	
		function addNotification(link){

			Effect.toggle(document.getElementById("notifications_settings"), 'slide');
			//Effect.SlideUp(document.getElementById("add_link"));
			
		}
		function delConfirm(email){
			var deleteit = confirm("Are you sure you want to delete this email association?");
			if(deleteit){
				window.location="user_emails.php?del=true&email=" + php_urlencode(email);
			}
		}
		
		// Function borrowwed from http://www.phpbuilder.com/board/showthread.php?t=10318476
		function php_urlencode (str) {
			str = escape(str);
			return str.replace(/[*+\/@]|%20/g,
				function (s) {
					switch (s) {
						case "*": s = "%2A"; break;
						case "+": s = "%2B"; break;
						case "/": s = "%2F"; break;
						case "@": s = "%40"; break;
						case "%20": s = "+"; break;
					}
				return s;
				}
			);
		}
		
		// Function borrowed from elia.wordpress.com/2007/01/18/overflow-smooth-scroll-with-scriptaculous/
		function moveTo(container, element){
		  Position.prepare();
		  container_y = Position.cumulativeOffset($(container))[1]
		  element_y = Position.cumulativeOffset($(element))[1]
		  new Effect.Scroll(container, {x:0, y:(element_y-container_y)});
		  return false;
		}
		
		function removeNotification(){
			Effect.toggle(document.getElementById("notifications_settings"), 'slide');
			//Effect.SlideUp(document.getElementById("add_link"));
			
		}
		function setInnerHTMLbyEle(element, message) {
		    //var element = document.getElementById(element);
		    removeChildrenFromNode(element);
		    var newdiv = document.createElement("div");
		    newdiv.innerHTML = message;
		    element.appendChild(newdiv);
		}

		//removeChildrenFromNode adapted from www.mikechambers.com/blog/2006/01/24/removing-html-element-children-with-javascript/
		function removeChildrenFromNode(node){
		   if(node == undefined ||
		        node == null)
		   {
		      return;
		   }
		   var len = node.childNodes.length;
			while (node.hasChildNodes())
			{
			  node.removeChild(node.firstChild);
			}
		}	
	</script>	
<?php require('nav.php') ?>		
<?php
function generateString($length=9) {
	$vowels = 'aeuyAEUY';
	$consonants = 'bdghjmnpqrstvzBDGHJLMNPQRSTVWXZ23456789';
	$string = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$string .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$string .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $string;
}


function primaryCheck(&$error_message){
	global $username,$email;
	if(isset($_GET['del'])){
		if (!isset($username)){
			$error_message = "You must be logged in to delete an association. ";
			return FALSE;
		}
		if(isset($_GET['email'])){
			$db = new PDO('sqlite:'.$DATABASE);	
			$sqlquery = "DELETE FROM emailassociations WHERE email = :email";
			$stmt = $db->prepare($sqlquery);	
			$stmt->bindValue(':email',$_GET['email'], PDO::PARAM_STR);
			if(!$stmt->execute()){
				$error_message ="Could not delete Association.";
				$db = null;
				return FALSE;
			}
			$db = null;
		}
		else{
			$error_message ="No email specified.";
			return FALSE;
		}
	}
	if(isset($_POST['add_email'])) {
		if (!isset($username)){
			$error_message = "You must be logged in to delete an association. ";
		}
		/*if(isset($_POST['username'])){
			$username = $_POST['username'];
		}
		else{
			die("No valid username specified while trying to add email association.");
		}*/
		if(isset($_POST['new_email'])){
			$email = $_POST['new_email'];
			// GET EMAIL ADDRESS FROM "FROM" (sometimes it might be the case you get something like Bob Smith <bobbyboy@yahoo.com> for "FROM")
		$pattern = '/^([a-z0-9])(([-a-z0-9._\+])*([a-z0-9]))*\@([a-z0-9])' . '(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
		preg_match($pattern,$email,$matches);
		if(!isset($matches[0])){
			$error_message ="Not a valid email.";
			return FALSE;
		}
		}
		else{
			$error_message ="No email specified while trying to add email association.";
			return FALSE;
		}
		$db = new PDO('sqlite:'.$DATABASE);	
		$sqlquery = "SELECT ROWID FROM emailassociations WHERE email = :email";
		$stmt = $db->prepare($sqlquery);
		$stmt->bindValue(':email',$email, PDO::PARAM_STR);
		$stmt->execute();		
		$res = $stmt->fetchAll();
		if(!empty($res)){
			$error_message = "Email is already associated to an account.";
			$db = null;
			return FALSE;
		}
		// Check to make sure user exists
		$sqlquery = "SELECT ROWID FROM user WHERE username = :username";
		$stmt = $db->prepare($sqlquery);	
		$stmt->bindValue(':username',$username, PDO::PARAM_STR);
		if(!$stmt->execute()){
			$error_message ="Specified user was not found in DB.";
			$db = null;
			return FALSE;
		}
		$res = $stmt->fetch();
		$userid = $res[0];
		// add the email association to the DB with activated set to 0. 
		$sqlquery = "INSERT INTO emailassociations (email,userid, activated) VALUES (:email,:userid, :activated)";
		$stmt = $db->prepare($sqlquery);
		$stmt->bindValue(':email',$email, PDO::PARAM_STR);
		$stmt->bindValue(':userid',$userid, PDO::PARAM_STR);
		$stmt->bindValue(':activated','0', PDO::PARAM_STR);
		if($stmt->execute() === FALSE){
			$error_message ="Could not add association to DB.";
			$db = null;
			return FALSE;
		}
		// Send a confirmation email to the user with a link to activate
		$sqlquery = "SELECT ROWID FROM emailassociations WHERE email = :email AND userid = :userid";
		$stmt = $db->prepare($sqlquery);
		$stmt->bindValue(':email',$email, PDO::PARAM_STR);
		$stmt->bindValue(':userid',$userid, PDO::PARAM_STR);
		$stmt->execute();
		$res = $stmt->fetch();
		$rowID = $res[0];
		$randStr = generateString(10);
		$hash = md5($rowID . $randStr);
		$to      = $email;
		$subject = 'Activate your associated email - What\'s Invasive';
		$message = "Dear $username,\nThanks for adding this account to your associated emails. To complete your activation, simply copy and paste the address below into your web browser. \n\n www.whatsinvasive.com/activation?val=" .urlencode($hash). "&row=$rowID&string=$randStr\nThank you again, and we look forward to receiving many email submissions from you in the future.\n\nSincerely,\nThe WhatsInvasive Team";
		$headers = 'From: emailactivation@whatsinvasive.com' . "\r\n" .
		    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
		    'X-Mailer: PHP/' . phpversion();
		mail($to, $subject, $message, $headers);
		$error_message = "Email address successfully associated, please check email for authentication instructions.";
		$db = null;
	}
	return TRUE;
}

$no_error = primaryCheck($error_message);
?>

<?php // if logged in already, show user page
	if (isset($username)):
		require('user_associations.php'); ?>	

<?php // if not logged in already, show login page
	else: ?>
	<div class="box span-6 last">
		<form action='login_new.php' method='POST'>
			<input type="hidden" name="requested_url" value="<?php echo($_SERVER["REQUEST_URI"]) ?>" id="requested_url">
			<div class="span-3">
				<label for="username">Username:</label>
			</div>
			<div class="span-3 last">
				<input type="text" name="username" id="username" size="10" value=" username  " onfocus="if(this.value==' username  '){this.value='';}" >
			</div>

			<div class="span-3">
				<label for="password">Password:</label>
			</div>
			<div class="span-3 last">
				<input type="password" name="password" id="password" size="10" value="  password  " onfocus="if(this.value=='  password  '){this.value='';}">
			</div>

			<hr />

			<div class="span-6 last">
				<input type="submit" name="submit" id="submit" value="Login">
			</div>
		</form>
	</div>
<?php endif ?>

<?php require('footer.php');
